// Create an input widget that takes only one digit
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:management/const/consts.dart';

class MyVerifyCode extends StatefulWidget {
  const MyVerifyCode(
      {super.key,
      this.hintText = '',
      required this.isDark,
      required this.countTime,
      required this.onSubmit,
      required this.onResend});

  final String hintText;
  final bool isDark;
  final int countTime;
  final void Function() onResend;
  final void Function(String newValue) onSubmit;

  static String WrongMessage = "Wrong";

  @override
  State<StatefulWidget> createState() => _MyVerifyCodeState();
}

class _MyVerifyCodeState extends State<MyVerifyCode> {
  final TextEditingController _fieldOne = TextEditingController();
  final TextEditingController _fieldTwo = TextEditingController();
  final TextEditingController _fieldThree = TextEditingController();
  final TextEditingController _fieldFour = TextEditingController();
  String _otp = '';
  String _buttonText = MyText.reSend.tr;
  Color backColor = MyColor.backBlue;
  Color backColorDark = MyColor.dark2;
  bool _canFocus = true;

  late Timer _timer;
  int _countdownTime = 0;

  void startCountdownTimer() {
    const oneSec = Duration(seconds: 1);

    callback(timer) => {
          setState(() {
            if (_countdownTime < 1) {
              _timer.cancel();
              _buttonText = MyText.reSend.tr;
              _canFocus = true;
            } else {
              _countdownTime = _countdownTime - 1;
              _buttonText = "Resend code in $_countdownTime s";
              _canFocus = false;
            }
          })
        };

    _timer = Timer.periodic(oneSec, callback);
  }

  void _handlePressed() {
    widget.onResend();
    _countdownTime = widget.countTime;
    startCountdownTimer();
  }

  void _handleSubmit() {
    _otp = _fieldOne.text + _fieldTwo.text + _fieldThree.text + _fieldFour.text;
    if (_otp.isNum && _otp.length == 4) {
      widget.onSubmit(_otp);
    }
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(widget.hintText,
            textAlign: TextAlign.center,
            style: Theme.of(context)
                .textTheme
                .bodyLarge
                ?.copyWith(fontWeight: FontWeight.w400)),
        const SizedBox(
          height: 60,
        ),
        // Implement 4 input fields
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            OtpInput(_fieldOne, true, widget.isDark ? backColorDark : backColor,
                textColor: widget.isDark ? MyColor.white : MyColor.black),
            OtpInput(
                _fieldTwo, false, widget.isDark ? backColorDark : backColor,
                textColor: widget.isDark ? MyColor.white : MyColor.black),
            OtpInput(
                _fieldThree, false, widget.isDark ? backColorDark : backColor,
                textColor: widget.isDark ? MyColor.white : MyColor.black),
            OtpInput(
                _fieldFour, false, widget.isDark ? backColorDark : backColor,
                textColor: widget.isDark ? MyColor.white : MyColor.black)
          ],
        ),
        const SizedBox(
          height: 60,
        ),
        SizedBox(
          child: TextButton(
              onPressed: _canFocus ? _handlePressed : () {},
              style: ButtonStyle(
                  textStyle: MaterialStateProperty.all(TextStyle(
                      color: widget.isDark ? MyColor.white : MyColor.primary)),
                  elevation: MaterialStateProperty.all(0),
                  minimumSize: MaterialStateProperty.all(const Size(100, 20))),
              child: Text(_buttonText)),
        ),
        const SizedBox(
          height: 200,
        ),
        SizedBox(
            width: double.infinity,
            height: 55,
            child: ElevatedButton(
                onPressed: () => _handleSubmit(),
                child: Text(MyText.submit.tr))),
        // Display the entered OTP code
      ],
    );
  }
}

class OtpInput extends StatelessWidget {
  final TextEditingController controller;
  final bool autoFocus;
  final Color backColor;
  final Color textColor;
  const OtpInput(this.controller, this.autoFocus, this.backColor,
      {Key? key, required this.textColor})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          color: backColor, borderRadius: BorderRadius.circular(12)),
      height: 55,
      width: 60,
      child: TextField(
        style: TextStyle(
            fontWeight: FontWeight.w700,
            fontSize: 20,
            height: 1.2,
            color: textColor),
        autofocus: autoFocus,
        textAlign: TextAlign.center,
        keyboardType: TextInputType.number,
        controller: controller,
        maxLength: 1,
        cursorColor: Theme.of(context).primaryColor,
        decoration: const InputDecoration(counterText: ''),
        onChanged: (value) {
          if (value.length == 1) {
            FocusScope.of(context).nextFocus();
          }
        },
      ),
    );
  }
}
